const Https = require('https');
const { execSync } = require('child_process');

const branchName = execSyncWithOutput('git symbolic-ref --short -q HEAD').trim();
const projectName = 'shb-pc-fe';
let userName = execSyncWithOutput('git config user.name').trim();

const statusTypeMap = {
  start: '构建开始',
  error: '构建失败',
  end: '构建结束',
};

function outsideWebhook(statusText, content) {
  const status = statusText || global.process.argv[2];
  const statusFormattedText = statusTypeMap[status] || '构建';

  const requestOptions = {
    host: 'oapi.dingtalk.com',
    method: 'POST',
    path: '/robot/send?access_token=95935df98a5ebe322f51cfbd7e3189e15292fd112175b9be61e52b828eca6aeb',
    headers: {
      'Content-Type': 'application/json',
    },
  };
  const postData = JSON.stringify({
    msgtype: 'text',
    text: {
      content: `售后宝前端 ${projectName} 项目 ${userName} 在 ${branchName} 分支 ${statusFormattedText} \n ${content}`,
    },
  });

  const req = Https.request(requestOptions);

  req.on('error', err => {
    throw new Error(err);
  });
  req.write(postData);
  req.end();
}
function execSyncWithOutput(command) {
  return execSync(command, { encoding: 'utf8' });
}

module.exports = {
  outsideWebhook,
};
